import { usePlanAuthority } from './usePlanAuthority';
import { useUserProfile } from './useUserProfile';
import { usePlanBaseApi } from './usePlanBaseApi';
import { watch, computed ,nextTick} from 'vue';
import { FilterExpression } from '../../covert';

export const usePagePlanApi = (Variable, emit) => {
  const {
    UserProfile,
    currectPlan,
    mixViewRefreshByData,
    modifyPlan,
    mappingProps,
    dataQueryID,
    pageID,
    sortCode,
    isReset,
    planIsChange,
    queryPlanList,
    $q,
    planName,
    targetName,
    changePlanFlag,
    showShare,
    proxyPlan,
    menuContent,
    openSubWarning,
    subPlan,
    TabsRef,
    renameProxy,
    showRenameDialog,
    saveAsPlan,
    isPublic,
    isDefault,
    showDialog,
    sharePlan,
    shareDetile,
    showShareDetil,
    queryPlanByShareUrl,
    isIgnore,
    LoadDataTime,
    instanceCode
  } = Variable;
  const { hasAuth, getSubStatus } = usePlanAuthority(Variable);
  const { getPageUserProfile } = useUserProfile(
    UserProfile,
    modifyPlan,
    pageID,
  );

  const { getDefaultPlan,GetQueryPlanV2 } = usePlanBaseApi(Variable, emit,'');
  const updateFilterComponent = async () => {
    const currentQueryPlan = JSON.parse(JSON.stringify(modifyPlan.value));
    try {
      if (
        currentQueryPlan.FilterShow &&
        JSON.parse(currentQueryPlan.FilterShow).FilterModel != 'Comp'
      ) {
       // const FilterContent: any = JSON.parse(currentQueryPlan.FilterContent);

        // const Filters: any = [];
        // if (JSON.parse(currentQueryPlan.FilterShow).FilterModel != 'Classic') {
        //   for (let i = 0; i < FilterContent.Filters.length; i++) {
        //     if (FilterContent.Filters[i].Value
        //       &&
        //       (!FilterContent.Filters[i].Value.join
        //         ||
        //         (FilterContent.Filters[i].Value.join
        //           &&
        //           FilterContent.Filters[i].Value.join('')
        //         )
        //       )
        //     ){
        //       Filters.push(FilterContent.Filters[i]);
        //       i++;
        //       if (FilterContent.Filters[i]) {
        //         Filters.push(FilterContent.Filters[i]);
        //       }
        //     } else {
        //       i++;
        //     }
        //   }
        //   FilterContent.Filters = Filters;
        // }

        mappingProps.filterInstance.setFilters(
          JSON.parse(
            currentQueryPlan.FilterShow || currentQueryPlan.FilterContent,
          ),
          JSON.parse(currentQueryPlan.FilterShow).FilterModel,
        );
      } else {
        mappingProps.filterInstance.setFilters(
          JSON.parse(
            currentQueryPlan.FilterShow || currentQueryPlan.FilterContent,
          ),
        );
      }

      return new Promise(resolve => {
        setTimeout(() => {
          synchronizationFilter(modifyPlan.value, true);
        }, 0);
        resolve(1);
      });
    } catch (error) {}
  };
  const getQueryPlanList = async () => {
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      let res = await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-GetQueryPlanListV3'),
        )}`,
        type: 'post',
        data: {queryPlanFilter:JSON.stringify({
          DQID: dataQueryID.value,
          pageID: pageID.value, //window.pageMetaData.ID,
          sortCode: sortCode.value ? sortCode.value : 'PlanOrder',
          BusinessTag:Funcs.GetUrlQuery('BusinessTag')
        }) },

      });
      if (queryPlanByShareUrl.value) {
        res.unshift(queryPlanByShareUrl.value);
      }
      return res;
    } else {
      return new Promise(resolve => {
        resolve([]);
      });
    }
  };
  let OnChangeToPublishOtherComponentsTimer: any = null;
  const OnChangeToPublishOtherComponents = async (currentQueryPlanChing?) => {
    if (OnChangeToPublishOtherComponentsTimer) {
      window.clearTimeout(OnChangeToPublishOtherComponentsTimer);
      OnChangeToPublishOtherComponentsTimer = null;
    }
    OnChangeToPublishOtherComponentsTimer = window.setTimeout(async () => {
      if (!isReset.value) {
        //扩展支持onchange 事件
        emit('changed', {
          hasAuth: hasAuth(),
          status: getSubStatus(),
        });
      } else {
        planIsChange.value = false;
      }

      if (LoadDataTime.value) {
        return (LoadDataTime.value = false);
      }

      const BeforeQuery: any = {};
      emit('beforeQuery', BeforeQuery);
if(mappingProps.mixViewInstance){
  try {
    //@ts-ignore
    if(window.Funcs){
      getPageUserProfile().then(res=>{
        mappingProps.mixViewInstance.setSchemeWithUserProfile(res?.data && res.data[0] && res.data[0].ConfigValue, modifyPlan.value)
      })
      
    }
  } catch (error) {}
}
     

      if (BeforeQuery.hasOwnProperty('cancel') && BeforeQuery.cancel) {
        try {
          //切换方案的时候主动清空
          mixViewRefreshByData.value
            ? mixViewRefreshByData.value({ List: [], Count: 0 })
            : null;
        } catch (error) {}

        return;
      }
      try {
        //筛选器自己check 不通过拦截请求
        if (
          mappingProps.filterInstance &&
          mappingProps.filterInstance.checkMust &&
          !mappingProps.filterInstance.checkMust()
        ) {
          return;
        }
      } catch (error) {}
      let charts
      try {
        if (mappingProps.mixViewInstance) {
          if (!modifyPlan.value.Charts) {
            /**
             * 2024年12月27日 图表配置下沉到多维视图图表视图展示时获取
             * BUG20241226180759100 【产品审查】LCP界面1.5s功能审查-FASR-GetChartInstanceApplys改为懒加载，用户点击图表视图时再发起请求
             *
            charts= GetChartInstanceApplys();
            */
          }
         
          
          try {
            //@ts-ignore
          mappingProps.mixViewInstance.registerAdvQueryWidget(Widget[instanceCode])
        } catch (error) {

        }
        mappingProps.mixViewInstance.setScheme(
          JSON.parse(JSON.stringify(modifyPlan.value))
        );
        if (!currentQueryPlanChing) {
          planIsChange.value = false;
        }
          // mappingProps.mixViewInstance.query()
        }
      } catch (error) {}
    },10);
  };
  const GetChartInstanceApplys = () => {
    if (!currectPlan?.value?.ContentID) return;
    return new Promise(resolve => {
      //@ts-ignore
      TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-GetChartInstanceApplys'),
          )}`,
          type: 'post',
          data: {
            targetType: 0,
            targetID: currectPlan.value.ContentID,
          },
        })
        .then(res => {

          currectPlan.value.Charts = res;
          modifyPlan.value.Charts = res;
          proxyPlan.value = JSON.stringify(modifyPlan.value);
          resolve([]);
        });
    });
  };
  const UpdateQueryPlan = async (queryPlanTarget, params) => {
    //@ts-ignore
    if (window.TFF) {
      if (params.hasOwnProperty('Name')) {
        params.Name = params.Name.trim();
        if (!params.Name.trim()) {
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.title.searchPlaceholder,
            'warning',
          );
          return;
        }
      }
      //@ts-ignore
      TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-UpdateQueryPlan'),
          )}`,
          type: 'post',
          data: {
            planID: queryPlanTarget.ID,
            param: JSON.stringify(params),
          },
        })
        .then(async () => {
          queryPlanList.value = await getQueryPlanList();
        })
        .catch(e => {});
    }
  };
  //新增或编辑
  const CreateOrUpdateQueryPlan = async (
    isSaveAs,
    queryPlanTarget,
    backupName,
  ) => {
    queryPlanTarget = Object.assign({}, queryPlanTarget);
    if (isSaveAs) {
      if(queryPlanTarget.ID== modifyPlan.value.ID){
        queryPlanTarget.FilterContent = _.cloneDeep(
          modifyPlan.value,
        ).FilterContent;
      }else{
         let filter= await GetQueryPlanV2(queryPlanTarget.ID);
         queryPlanTarget.FilterContent = filter?.FilterContent
         queryPlanTarget.FilterShow = filter?.FilterShow
      }
      delete queryPlanTarget.ID;
      delete queryPlanTarget.WarningID;
      delete queryPlanTarget.IsSystem;
      queryPlanTarget.IsAuth = true;
    }
    if (!queryPlanTarget.Name) {
      //@ts-ignore
      Funcs.Notify(
        $q.lang.selectHelper.warning,
        $q.lang.queryPlan.title.searchPlaceholder,
        'warning',
      );
      return;
    }
    queryPlanTarget.Name = queryPlanTarget.Name.trim();
    queryPlanTarget.DQID = dataQueryID.value;
    queryPlanTarget.PageID = pageID.value; //window.pageMetaData.ID
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-CreateOrUpdateQueryPlanV2'),
          )}`,
          type: 'post',
          data: {
            queryPlan: JSON.stringify(queryPlanTarget),
            BusinessTag:Funcs.GetUrlQuery('BusinessTag')
          },
        })
        .then(async res => {
          if (res.state == 0) {
            //@ts-ignore
            Funcs.Notify(
              $q.lang.selectHelper.warning,
              $q.lang.queryPlan.notify.fail.format(
                isSaveAs
                  ? $q.lang.queryPlan.title.saveAs
                  : $q.lang.queryPlan.title.save,
                res.errmsg,
              ),
              'warning',
            );

            return;
          }
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.notify.success.format(
              isSaveAs
                ? $q.lang.queryPlan.title.saveAs
                : $q.lang.queryPlan.title.save,
            ),
            'success',
          );
          queryPlanList.value = await getQueryPlanList();

          let plan = queryPlanList.value.find(
            item => item.ID == res.queryPlanID,
          );
          //查询一遍
          plan = await GetQueryPlanV2(plan.ID)
          plan.isReady = true
          modifyPlan.value = Object.assign({}, plan);
          currectPlan.value = Object.assign({}, plan);
          setTimeout(() => {
            planIsChange.value = false;
          }, 100);

          if (backupName) {
            planName.value = targetName.value;
          }
          showDialog.value = false;
        })
        .catch(e => {
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.notify.fail.format(
              isSaveAs
                ? $q.lang.queryPlan.title.saveAs
                : $q.lang.queryPlan.title.save,
              e.message,
            ),
            'warning',
          );
        });
    }
  };
  //置顶
  const TopQueryPlan = async queryplan => {
    //@ts-ignore
    if (window.TFF) {
      const params = {
        topType: queryplan.TopTime == '0001-01-01 00:00:00' ? 0 : 1,
        planID: queryplan.ID,
      };
      //@ts-ignore
      await TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-TopQueryPlan'),
          )}`,
          type: 'post',
          params,
        })
        .then(async () => {
          queryPlanList.value = await getQueryPlanList();
        });
    }
  };
  //批量保存（拖拽调整顺序）
  const SaveQueryPlans = async queryplanList => {
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      queryPlanList.value = await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-SaveQueryPlans'),
        )}`,
        type: 'post',
        data: {
          queryPlans: JSON.stringify(queryplanList),
        },
      });
    }
  };
  //不需要暴漏
  const CancleScheduleJobSubscription = subscriptionID => {
    //@ts-ignore
    return TFF.common.ajax.getDataAsync({
      //@ts-ignore
      url: `${Funcs.FasRequestTagAdd(
        //@ts-ignore
        TFF.common.ajax.getServiceUrl('FASR-CancleScheduleJobSubscription'),
      )}`,
      type: 'post',
      data: {
        subscriptionID: subscriptionID,
      },
    });
  };
  const deleteQueryPlan = async (planId, WarningID) => {
    //@ts-ignore
    if (window.TFF) {
      if (WarningID) {
        CancleScheduleJobSubscription(WarningID);
      }
      //@ts-ignore
      await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-DeleteQueryPlan'),
        )}`,
        type: 'post',
        data: {
          id: planId,
        },
      });
    }
  };
  //同步筛选器内容
  const synchronizationFilter = (plan, notNotify?) => {
    const Scheme = mappingProps.filterInstance
      ? mappingProps.filterInstance.getFilters()
      : null;
    if (!Scheme) return;

    plan.FilterContent = JSON.stringify(Scheme.Scheme);
    plan.Content = JSON.stringify(Scheme.Scheme);
    plan.FilterShow = JSON.stringify(Scheme.Groups);
    plan.SortContent = plan.SortContent || `[]`;
    plan.CrossColumn = plan.CrossColumn || `[]`;
    if (!notNotify) {
      proxyPlan.value = JSON.stringify(plan);
      planIsChange.value = true;
    }else{
      proxyPlan.value = JSON.stringify(plan);
    }
  };
  const shareToOther = async (shareList, plan) => {
    const shareUsers = [];
    shareList
      ? shareList.forEach(item => {
          const obj = {
            UserID: item.UserID,
            UserName: item.RealName,
          };
          //@ts-ignore
          shareUsers.push(obj);
        })
      : [];
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      const data = await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-ShareQueryPlan'),
        )}`,
        type: 'post',
        data: {
          queryPlan: JSON.stringify(plan),
          shareUsers: JSON.stringify(shareUsers),
          BusinessTag:Funcs.GetUrlQuery('BusinessTag')
        },
      });

      if (data.state == 1) {
        queryPlanList.value = await getQueryPlanList();
        const proxyplanIsChange = planIsChange.value
        modifyPlan.value.ShareUsers = shareUsers
        modifyPlan.value.PlanRange = 2
        nextTick(()=>{
          setTimeout(() => {
            planIsChange.value = proxyplanIsChange
          }, 0);

        })
        //@ts-ignore
        Funcs.Notify(
          $q.lang.selectHelper.warning,
          $q.lang.queryPlan.notify.shareSuccess,
          'success',
        );

        showShare.value = false;
      } else {
        return;
      }
    }
  };
  //同步多维视图
  const synchronizationMixView = plan => {
    const Scheme = mappingProps.mixViewInstance
      ? mappingProps.mixViewInstance.getScheme()
      : null;
    if (!Scheme) return;
    //多维视图更新
    for (const i in Scheme) {
      if (
        i != 'DefaultView' ||
        (i == 'DefaultView' && (Scheme[i] || Scheme[i] == 0))
      ) {
        plan[i] = Scheme[i];
      }
    }
    plan.IsChartChange = true;
  };
  //方案更新
  const updateAdvQuery = async (params, forbidSave, query) => {
    //筛选器更新条件
    if (params) {
      synchronizationFilter(modifyPlan.value);
    } else {
      synchronizationMixView(modifyPlan.value);
    }
    //触发刷新
    if (query) {
      OnChangeToPublishOtherComponents(true);
    }
    if (!forbidSave) {
      changePlanFlag.value = true;
      planIsChange.value = true;


    } else {
      changePlanFlag.value = false;
    }
  };
  let planChangeDelay = null;
  const queryPlanByOtherComponent = reset => {
    if (reset) {
      isReset.value = true;
      modifyPlan.value = JSON.parse(JSON.stringify(currectPlan.value));

      updateFilterComponent().then(() => {
        OnChangeToPublishOtherComponents(false);
        //planIsChange.value = false;
      });
      setTimeout(() => {
        //planIsChange.value = false;
        isReset.value = false;
      }, 100);
      return;
    }
    // 获取筛选器Scheme
    const planChangeProxy = planIsChange.value;
    if (planChangeDelay) {
      window.clearTimeout(planChangeDelay);
      planChangeDelay = null;
    }
    synchronizationMixView(modifyPlan.value);
    synchronizationFilter(modifyPlan.value, true);
    proxyPlan.value = JSON.stringify(modifyPlan.value);

    setTimeout(() => {
      planIsChange.value = planChangeProxy;
    }, 10);
    const filterScheme = mappingProps.getFilterScheme
      ? mappingProps.getFilterScheme()
      : null;
    const sortScheme = modifyPlan.value.ListViewSet
      ? JSON.parse(modifyPlan.value.ListViewSet).sortColumns
      : [];
    const BeforeQuery = {
      cancel: false,
    };
    emit('beforeQuery', BeforeQuery);

    if (BeforeQuery.hasOwnProperty('cancel') && BeforeQuery.cancel) {
      //切换方案的时候主动清空
      mixViewRefreshByData.value
        ? mixViewRefreshByData.value({ List: [], Count: 0 })
        : null;
      return;
    }
    //筛选器自己check 不通过拦截请求
    if (
      mappingProps.filterInstance &&
      mappingProps.filterInstance.checkMust &&
      !mappingProps.filterInstance.checkMust()
    ) {
      return;
    }
    mappingProps.mixViewInstance && mappingProps.mixViewInstance.query
      ? mappingProps.mixViewInstance.query(filterScheme, sortScheme)
      : null;
  };
  const resetMixViewSort = async () => {
    //@ts-ignore
    if(window.Funcs){
      getPageUserProfile().then(res=>{
        mappingProps.mixViewInstance.setSchemeWithUserProfile(res?.data && res.data[0] && res.data[0].ConfigValue)
      })
      
    }
    if (modifyPlan.value.ListViewSet) {
      const ListViewSet = JSON.parse(modifyPlan.value.ListViewSet);
      if (currectPlan.value.ListViewSet) {
        ListViewSet.sortColumns = JSON.parse(
          currectPlan.value.ListViewSet,
        )?.sortColumns;
      }
      modifyPlan.value.ListViewSet = JSON.stringify(ListViewSet);
    }

    mappingProps.mixViewInstance.setScheme(
      JSON.parse(JSON.stringify(modifyPlan.value)),
      
    );
  };
  const planOperate = async e => {
    if (e.type == 'sub') {
      menuContent.value.hide();
      openSubWarning.value = true;
      subPlan.value =
        e.plan.ID == modifyPlan.value.ID ? modifyPlan.value : e.plan;
    } else if (e.type == 'edit') {
      TabsRef.value.currentTabIndex = 0;
      modifyPlan.value = Object.assign({}, e.plan);
    } else if (e.type == 'rename') {
      renameProxy.value = Object.assign({}, e.plan);
      menuContent.value.hide();
      targetName.value = JSON.parse(JSON.stringify(e.plan)).Name;
      return (showRenameDialog.value = true);
    } else if (e.type == 'saveAs') {
      menuContent.value.hide();
      saveAsPlan.value = Object.assign({}, e.plan);
      const plan = Object.assign({}, e.plan);
      setTimeout(() => {
        //@ts-ignore
        window.saveAsPlan = saveAsPlan.value;
        targetName.value = plan.Name + '_copy';
        isPublic.value = plan.PlanRange == '0' && plan.IsAuth;
        isDefault.value = false;
        showDialog.value = true;
      }, 10);
      return;
    } else if (e.type == 'save') {
      menuContent.value.hide();
      e.plan = Object.assign({}, e.plan);
      if (!e.plan.Name) {
        //@ts-ignore
        Funcs.Notify(
          $q.lang.selectHelper.warning,
          $q.lang.queryPlan.title.searchPlaceholder,
          'warning',
        );
        return;
      }
      synchronizationMixView(e.plan);
      synchronizationFilter(e.plan, true);
      setTimeout(async () => {
        await CreateOrUpdateQueryPlan(false, e.plan, null);
        modifyPlan.value = Object.assign({}, e.plan);
        planIsChange.value = false;
      }, 0);
    } else if (e.type == 'share') {
       if(!e.plan.ShareUsers||!e.plan.ShareUsers.length){
          let ShareUsers =  await GetQueryPlanV2(e.plan.ID)
          e.plan.ShareUsers = ShareUsers.ShareUsers||[]
        }
      sharePlan.value = e.plan;
      showShare.value = true;
    } else if (e.type == 'top') {
      TopQueryPlan(e.plan);
    } else if (e.type == 'default') {
      e.plan.IsDefault = !e.plan.IsDefault;
      await UpdateQueryPlan(e.plan, {
        Default: e.plan.IsDefault,
      });
    } else if (e.type == 'delete') {
      //@ts-ignore
      Funcs.Confirm(
        $q.lang.selectHelper.warning,
        $q.lang.queryPlan.dialog.deletePlan,
        async () => {
          await deleteQueryPlan(e.plan.ID, e.plan.WarningID);

          getQueryPlanList().then(res => {
            queryPlanList.value = res;
            if (
              e.plan.ID == modifyPlan.value.ID &&
              e.plan.ID == currectPlan.value.ID
            ) {
              modifyPlan.value = currectPlan.value = null;
              getDefaultPlan();
            }
            // if (!modifyPlan.value && !currectPlan.value) {

            // }
          });
        },
        () => {},
        true,
        { type: 'warning' },
      );
    } else if (e.type == 'moveDown' || e.type == 'moveUp') {
      const type = e.type == 'moveDown' ? 1 : -2;
      let Target = JSON.parse(JSON.stringify(queryPlanList.value));
      //当前位置
      const index = Target.findIndex(item => item.ID == e.plan.ID);
      //删除
      Target = Target.filter(item => item.ID != e.plan.ID);
      if (type == -2) {
        if (index - 1 <= 0) {
          Target.unshift(e.plan);
        } else {
          Target.splice(index - 1, 0, e.plan);
        }
      } else {
        Target.splice(index + 1, 0, e.plan);
      }

      await SaveQueryPlans(
        Target.map(item => {
          return {
            ID: item.ID,
            PlanRange: item.PlanRange,
            Name: item.Name,
          };
        }),
      );
      queryPlanList.value = Target;
    } else if (e.type == 'shareDetail') {
      if(!e.plan.ShareUsers||!e.plan.ShareUsers.length){
        let ShareUsers =  await GetQueryPlanV2(e.plan.ID)
        e.plan.ShareUsers = ShareUsers.ShareUsers||[]
      }
      menuContent.value.hide();
      shareDetile.value = e.plan;
      showShareDetil.value = true;
    }
  };
  const queryPlanSave = () => {
    CreateOrUpdateQueryPlan(false, modifyPlan.value, null);
  };
  const queryPlanSaveAs = (isAdd) => {

    planOperate({ type: 'saveAs', plan: modifyPlan.value ,isAdd});
  };
  const filterExpression = computed(() => {
    if( mappingProps.filterInstance&&mappingProps.filterInstance.enableQuickFilter==='1'&&mappingProps.filterInstance.FilterIsClassic){
      return JSON.stringify(mappingProps.filterInstance.getAdvanceFilter())
    }
    
    let Filters = [];
    try {
      Filters = JSON.parse(JSON.stringify(modifyPlan.value));
    } catch (error) {}
    return FilterExpression(Filters, mappingProps.fields);
  });
  const sortExpression = computed(() => {
    if (!modifyPlan.value) return '';
    const sortScheme =
      modifyPlan.value.ListViewSet &&
      JSON.parse(modifyPlan.value.ListViewSet).sortColumns
        ? JSON.parse(modifyPlan.value.ListViewSet).sortColumns
        : [];
    const rt = sortScheme.map(m => {
      const cf = mappingProps.fields.find(f => f.fieldAlias == m.value);
      return {
        SortSource: cf.DataQuerySourceID,
        SortColumn: cf.fieldCode,
        SortType: m.sortOrder == 'asc' ? 0 : 1,
      };
    });
    return JSON.stringify(rt);
  });
  watch(
    () => modifyPlan.value,
    async (newValue, oldValue) => {
      if (!newValue || !newValue.ID) return;
      if (proxyPlan.value == JSON.stringify(newValue)) {
        return;
      }
      // if(!newValue.isReady){
      //   let plan = await GetQueryPlanV2(newValue.ID)
      //   plan.isReady = true
      //   modifyPlan.value = plan
      //   return
      // }
      proxyPlan.value = JSON.stringify(newValue);
      planName.value = newValue.Name;
      if (!oldValue || !oldValue.ID) {

        emit('change', newValue);
        //updateMixedviewComponent();
        updateFilterComponent().then(() => {
          OnChangeToPublishOtherComponents(false);
          setTimeout(() => {
            //
            proxyPlan.value == JSON.stringify(modifyPlan.value);
          }, 0);
        });
        isIgnore.value = false;
        return;
      }
      if (newValue.ID != oldValue?.ID) {
        mappingProps.filterInstance?.clearQuckFilterFilters()
    
        planIsChange.value = false;
        emit('change', newValue);
        //updateMixedviewComponent();
        updateFilterComponent().then(() => {
          OnChangeToPublishOtherComponents(false);
          setTimeout(() => {
            //planIsChange.value = false;
            proxyPlan.value == JSON.stringify(modifyPlan.value);
          }, 0);
        });
        isIgnore.value = false;
        return;
      }

      if (isReset.value) return;
      proxyPlan.value = JSON.stringify(newValue);
      changePlanFlag.value = true;
      planIsChange.value = true;
      //eval('console.log(814)')
      //eval('console.trace()')
    },
    {
      immediate: true,
      deep: true,
    },
  );
  return {
    updateFilterComponent,
    getQueryPlanList,
    OnChangeToPublishOtherComponents,
    UpdateQueryPlan,
    CreateOrUpdateQueryPlan,
    TopQueryPlan,
    SaveQueryPlans,
    deleteQueryPlan,
    updateAdvQuery,
    shareToOther,
    queryPlanByOtherComponent,
    resetMixViewSort,
    synchronizationMixView,
    synchronizationFilter,
    filterExpression,
    sortExpression,
    planOperate,
    queryPlanSave,
    queryPlanSaveAs,
  };
};
